<?php

namespace app\index\controller;

use think\Controller;
use think\Db;

/**
 * 支付回调类
 **/
class Notify extends Controller
{
    /**
     * 回调处理：
     * 1：支付状态改为已支付
     * 2：修改优惠券为已使用状态
     * 3：分佣（分享官，城市合伙人）
     * */
    public function notice()
    {
        $data = json_decode(json_encode(simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        file_put_contents(RUNTIME_PATH . 'pay.txt', json_encode($data, JSON_UNESCAPED_UNICODE));

        //业务处理代码请自行实现
        if ($data['result_code'] == 'SUCCESS' && $data['return_code'] == 'SUCCESS') {

            //接收附加数据
            $json_attach = $data['attach'];
            $attach_arr = json_decode($json_attach, true);

            //订单号
            $order_sn = $data['out_trade_no'];

            //查询订单支付状态；0：未支付；1：已支付
            $is_pay = Db::name('order')->where(['pay_order_sn' => $order_sn])->value('is_pay');
            if ($is_pay == 0) {
                Db::startTrans();
                try {
                    $this->doOrder($order_sn);

                    echo 'SUCCESS';
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }

        }
    }

    /**
     * 支付成功处理订单业务逻辑
     * @param string $order_sn 支付订单号
     * */
    public function doOrder($order_sn)
    {
        $order_info = Db::name('order')->where(['pay_order_sn' => $order_sn])->find();

        $order_id = $order_info['id'];
        $user_id = $order_info['user_id'];
        $coupon_id = $order_info['coupon_id'];

        $time = time();

        $user_info = Db::name('user')->where(['id' => $user_id])->find();

        // 1：修改订单支付状态
        $update_order_data = [
            'is_pay' => 1,
            'status' => 2,
            'pay_time' => $time,
            'update_time' => $time
        ];
        Db::name('order')->where(['id' => $order_id])->update($update_order_data);

        // 2：修改优惠券为已使用状态
        if ($coupon_id) Db::name('user_coupon')->where(['id' => $coupon_id])->update(['status' => 2, 'update_time' => $time]);

        $vice_order_list = Db::name('vice_order')->where(['order_id' => $order_id])->select();
        if ($vice_order_list) {
            foreach ($vice_order_list as &$v) {
                // 3：增加销量
                Db::name('goods')->where(['id' => $v['goods_id']])->setInc('sales_count', $v['count']);

                // 此行请勿删除
                cache('sku_' . $v['goods_id']);

                // 4：减库存
                Db::name('sku_value')->where(['goods_id' => $v['goods_id'], 'sku_id' => $v['sku_id']])->setDec('stock', $v['count']);
            }
        }

        // 3：分佣（分享官，城市合伙人）
        if ($user_info['mobile'] && $order_info['order_sn'] && $order_info['pay_price']) {
            file_get_contents('https://meimei.lizaonet.com/index/Api/doShopOrderNotice/mobile/' . $user_info['mobile'] . '/order_sn/' . $order_info['order_sn'] . '/order_price/' . $order_info['pay_price']);
        }
    }
}